package day13;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author: 王丹
 * @create: 2021-07-06 10:39
 **/
//waitNanos(long nanosTimeout)超时之前被唤醒
public class Demo8 {

    static ReentrantLock lock = new ReentrantLock();
    static Condition condition = lock.newCondition();

    public static class T extends Thread {
        public void run() {
            lock.lock();
            try {
                System.out.println(System.currentTimeMillis() + "," + this.getName() + ":start");
                long await = condition.awaitNanos(TimeUnit.SECONDS.toNanos(5));
                System.out.println(System.currentTimeMillis());
                System.out.println("await:" + await);
                System.out.println(System.currentTimeMillis() + "," + this.getName() + ":end");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
                System.out.println("lock.unlock()");
            }
        }
    }

    /**
     * 结果分析;t1中调用await休眠5秒，主线程休眠1秒之后，调用signal()唤醒线程t1，await方法返回正数，
     * 表示返回时距离超时时间还有多久，将近4秒，返回正数表示，线程在超时之前被唤醒了。
     */
    public static void main(String[] args) throws InterruptedException {
        T t1 = new T();
        t1.setName("t1");
        t1.start();
        //休眠1秒之后,能够先执行线程t1的awaitNanos方法。如果没有休眠一秒钟，那么就会执行主线程的condition.signal()方法
        TimeUnit.SECONDS.sleep(1);
        lock.lock();
        try {
            condition.signal();
            System.out.println(Thread.currentThread().getName() + "condition.signal()");
        } finally {
            lock.unlock();
        }
    }
}
